<template>
  <div class="department">
    <page-search
      :searchConfig="searchConfig"
      @resetClick="handleSearchReset"
      @queryClick="handleSearchQuery"
    />
    <page-content
      :content-config="contentConfig"
      ref="contentRef"
      @createRecord="handleCreateRecord"
      @editRecord="handleEditRecord"
    >
      <template #handlerId="scope">
        {{ findParentDepartName(scope.row.parentId) }}
      </template>
    </page-content>
    <page-modal ref="modalRef" :modal-config="modalConfigRef" />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import searchConfig from '@/views/main/system/department/config/search.config';
import contentConfig from '@/views/main/system/department/config/content.config';
import { useMainStore } from '@/store/mian';
import { storeToRefs } from 'pinia';
import modalConfig from '@/views/main/system/department/config/modal.config';
import usePageContent from '@/hooks/usePageContent';
import usePageModal from '@/hooks/usePageModal';

const { contentRef, handleSearchReset, handleSearchQuery } = usePageContent();
const { modalRef, handleCreateRecord, handleEditRecord } = usePageModal();

/** 获取到store */
const mainStore = useMainStore();
const { stateEntireDepartments } = storeToRefs(mainStore);

/**
 * @function findParentDepartName content组件中获取父部门名称，该方法提供给子组件page-content使用
 * @param parentId 父部门id
 */
function findParentDepartName(parentId: number) {
  let parentName = '';
  if (stateEntireDepartments.value) {
    for (let i = 0; i < stateEntireDepartments.value.length; i++) {
      if (stateEntireDepartments.value[i].id === parentId) {
        parentName = stateEntireDepartments.value[i].name;
      }
    }
  }
  return parentName;
}

/** 因为modal组件需要父部门id，所以需要动态获取，使用computed让其变为响应式，此逻辑是该组件特有，不用抽取hooks */
const modalConfigRef = computed(() => {
  const departments = stateEntireDepartments.value?.map((item) => {
    return { label: item.name, value: item.id };
  });
  if (departments !== undefined) {
    modalConfig.formItems.forEach((item) => {
      if (item.prop === 'parentId' && item.options?.length === 0) {
        item.options.push(...departments);
      }
    });
  }
  return modalConfig;
});
</script>

<style scoped lang="scss">
.department {
}
</style>
